package com.asset.service.impl;

import com.asset.mapper.CategoryMapper;
import com.asset.pojo.Category;
import com.asset.service.CategoryService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 分类信息管理服务实现类
 * @author 11725
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public PageResult<Category> selectByPage(Integer page, Integer rows, Boolean selectAll) {
        if (selectAll == null) {
            // 分页
            PageHelper.startPage(page, rows);
        }

        // 查询
        List<Category> categoryList = categoryMapper.selectAll();

        // 空值校验
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new RuntimeException("无匹配的分类信息");
        }

        // 获取分页信息
        PageInfo<Category> info = new PageInfo<>(categoryList);

        return new PageResult<>(info.getTotal(), categoryList);
    }

    @Override
    public Category selectById(Long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            throw new AssetManageException(AssetExceptionEnum.CATEGORY_INVALID);
        }

        return category;
    }

    @Override
    public List<Category> selectByIds(List<Long> ids) {
        return categoryMapper.selectByIdList(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Category category) {
        // 存在上级分类时
        if (category.getPid() != 0) {
            log.info("[分类服务]查询上级分类信息，pid:{}", category.getPid());
            Category parent = categoryMapper.selectByPrimaryKey(category.getPid());
            // 判断上级分类是否存在
            if (parent == null) {
                log.error("[分类服务]无效的上级分类编号：{}", category.getPid());
                throw new AssetManageException(AssetExceptionEnum.PARENT_CATEGORY_NOT_FOUND);
            }
            // 设置最小使用年限
            category.setYears(parent.getYears());
        }
        // 参数处理
        category.setId(null);
        category.setStatus(null);

        // 新增
        categoryMapper.insertSelective(category);
    }

    @Override
    public void update(Category category) {

    }

    @Override
    public void delete(Long id) {

    }
}









